<template>
  <div>
    <div class="supplier" v-if="!materialAddShow && !evaluateAddShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-hasPermi="['system:user:query']"
          class="btn search"
          @click="getMaterialList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-hasPermi="['system:user:add']"
          class="btn search"
          @click="
            materialAddShow = true;
            pageType = 'add';
          "
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增</el-button
        >
      </div>
      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item">
          <el-input
            clearable
            v-model="params.userName"
            class="search-input"
            placeholder="请输入用户账号"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.nickName"
            class="search-input"
            placeholder="请输入用户姓名"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.phonenumber"
            class="search-input"
            placeholder="请输入手机号码"
          ></el-input>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.status"
            placeholder="请选择用户状态"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="创建开始日期"
            end-placeholder="创建结束日期"
          ></el-date-picker>
        </div>
      </div>
      <div class="material-container">
        <!--分类数据-->
        <div class="class-container">
          <div class="class-top">
            <el-input
              v-model="className"
              placeholder="搜索部门"
              clearable
              class="class-input"
            />
          </div>
          <div class="head-container">
            <el-tree
              :data="deptOptions"
              :props="{ label: 'label', children: 'children' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="deptTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
            />
          </div>
        </div>
        <div style="width: 85%">
          <!-- 表格数据 -->
          <el-table
            v-loading="loading"
            :data="materialList"
            border
            height="64vh"
            :header-cell-style="{ 'text-align': 'center', background: 'red' }"
          >
            <!-- 操作模式 -->
            <el-table-column
              label="操作"
              :show-overflow-tooltip="true"
              width="210px"
            >
              <template #default="{ row }">
                <div class="table-operate">
                  <el-icon
                    v-hasPermi="['system:user:edit']"
                    title="编辑"
                    color="#FFB700"
                    class="table-icon"
                    :size="20"
                    @click="handleOperate('edit', row)"
                  >
                    <Edit />
                  </el-icon>
                  <el-icon
                    v-hasPermi="['system:user:detail']"
                    title="查看详情"
                    color="#007CEF"
                    class="table-icon"
                    :size="20"
                    @click="handleOperate('detail', row)"
                  >
                    <Document />
                  </el-icon>
                  <el-icon
                    v-hasPermi="['system:user:resetPwd']"
                    title="重置密码"
                    color="#007CEF"
                    class="table-icon"
                    :size="20"
                    @click="handleOperate('resetPwd', row)"
                  >
                    <Key />
                  </el-icon>
                  <el-icon
                    v-hasPermi="['system:user:edit']"
                    title="分配角色"
                    color="#007CEF"
                    class="table-icon"
                    :size="20"
                    @click="handleOperate('AssigningRoles', row)"
                  >
                    <CircleCheck />
                  </el-icon>
                  <el-icon
                    v-hasPermi="['system:user:remove']"
                    title="删除"
                    color="#E33838"
                    class="table-icon"
                    :size="20"
                    @click="handleOperate('delete', row)"
                  >
                    <Delete />
                  </el-icon>
                </div> </template
            ></el-table-column>
            <el-table-column
              type="index"
              label="序号"
              :index="indexMethod"
              width="70"
              align="center"
            />
            <el-table-column label="用户编号" key="userId" prop="userId" />
            <el-table-column
              label="用户账号"
              align="center"
              key="userName"
              prop="userName"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="用户姓名"
              align="center"
              key="nickName"
              prop="nickName"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="部门"
              align="center"
              key="deptName"
              prop="dept.deptName"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="手机号码"
              key="phonenumber"
              prop="phonenumber"
              width="120"
            />
            <el-table-column label="状态" align="center" key="status">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-value="0"
                  inactive-value="1"
                  @change="handleStatusChange(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column
              label="创建人"
              align="center"
              key="createBy"
              prop="createBy"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="创建时间"
              align="center"
              prop="createTime"
              width="160"
            >
              <template #default="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getMaterialList"
      />
    </div>
    <UserAdd
      v-if="materialAddShow"
      ref="materialAddRef"
      v-model:materialAddShow="materialAddShow"
      @updateEvaluateAddShow="evaluateAddShow = false"
      @refreshList="getMaterialList"
      :pageType="pageType"
    />
  </div>
</template>

<script setup>
const router = useRouter();
import {
  changeUserStatus,
  listUser,
  resetUserPwd,
  delUser,
  getUser,
  updateUser,
  addUser,
  deptTreeSelect,
} from "@/api/system/user";
import UserAdd from "./userAdd";
const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_user_sex } = proxy.useDict(
  "sys_normal_disable",
  "sys_user_sex"
);
import { getDictsApi } from "@/api/dict";
import { getMaterialClassListApi } from "@/api/information/materialClass";
import { ElMessage, ElMessageBox } from "element-plus";
// 搜索参数
const params = reactive({
  userName: undefined,
  phonenumber: undefined,
  status: undefined,
  deptId: undefined,
  pageNum: 1,
  pageSize: 50,
});
const deptOptions = ref(undefined);
const loading = ref(false);
const materialAddShow = ref(false);
const evaluateAddShow = ref(false);
const materialList = ref([]);
const total = ref(0);
const className = ref("");
const materialAddRef = ref(null);
const pageType = ref("");
const stockTypeList = ref([]);
const classOptions = ref(undefined);
const dateRange = ref([]);

const getMaterialList = async () => {
  try {
    loading.value = true;
    listUser(proxy.addDateRange(params, dateRange.value)).then((res) => {
      if (res.code == 200) {
        materialList.value = res.rows;
        total.value = res.total;
        loading.value = false;
      }
    });
  } catch {
    loading.value = false;
  }
};
/** 获取分类列表  */
const getMaterialClassList = async () => {
  const res = await getMaterialClassListApi();
  res.rows.unshift({
    categoryId: 0,
    categoryName: "全部",
    parentId: null,
  });
  res.rows.forEach((item) => {
    item.id = item.categoryId;
  });
  classOptions.value = proxy.handleTree(res.rows, "id");
};

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 根据名称筛选分类树 */
watch(className, (val) => {
  proxy.$refs["deptTreeRef"].filter(val);
});

/** 节点单击事件 */
function handleNodeClick(data) {
  params.deptId = data.id;
  getMaterialList();
}

// 放大图片
const showImg = (img) => {
  let imgArr = [];
  imgArr.push(img);
  return imgArr;
};

// 操作
const handleOperate = async (type, row) => {
  switch (type) {
    case "detail":
      materialAddShow.value = true;
      pageType.value = "detail";
      nextTick(() => {
        materialAddRef.value.handleDetailInfo(row.userId);
      });
      break;
    case "edit":
      materialAddShow.value = true;
      pageType.value = "edit";
      nextTick(() => {
        materialAddRef.value.handleDetailInfo(row.userId);
      });
      break;
    case "AssigningRoles":
      const userId = row.userId;
      router.push("/system/user-auth/role/" + userId);
      break;
    case "resetPwd":
      proxy
        .$prompt('请输入"' + row.userName + '"的新密码', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          confirmButtonClass: "confirmBtnClass",
          cancelButtonClass: "cancelBtnClass",
          closeOnClickModal: false,
          inputPattern: /^.{5,20}$/,
          inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        })
        .then(({ value }) => {
          resetUserPwd(row.userId, value).then((response) => {
            proxy.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        })
        .catch(() => {});
      break;

    case "delete":
      ElMessageBox.confirm("此操作将删除该用户，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await delUser(row.userId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getMaterialList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};

async function getDicts() {
  await getDictsApi("stock_type").then((res) => {
    // 存货类型
    if (res.code === 200) {
      stockTypeList.value = res.data;
    }
  });
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data;
  });
}

/** 用户状态修改  */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.userName + '"用户吗?')
    .then(function () {
      return changeUserStatus(row.userId, row.status);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.status = row.status === "0" ? "1" : "0";
    });
}

// -----------------------------------  序号  ----------------------------------
function indexMethod(index) {
  // 当前页码
  const currentPage = params.pageNum;
  // 每页显示的数据条数
  const pageSize = params.pageSize;
  // 当前行的实际索引
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  // 如果当前行的索引大于等于当前页的最大索引，
  // 则使用当前行的实际索引，否则使用当前行的原始索引
  return truelndex;
}

onMounted(() => {
  getMaterialList();
  getMaterialClassList();
  getDicts();
});
</script>
<style>
.confirmBtnClass {
  color: #fff;
  width: 90px;
  height: 34px;
  background: #007cef;
}
.confirmBtnClass:hover,
.confirmBtnClass:active,
.confirmBtnClass:focus {
  color: #fff;
  background: #007cef;
}
.cancelBtnClass {
  border: 1px solid #999999;
  color: #333333;
  width: 90px;
  height: 34px;
  background: #f3f3f3;
}
.cancelBtnClass:hover,
.cancelBtnClass:active,
.cancelBtnClass:focus {
  border: 1px solid #999999;
  color: #333333;
  background: #f3f3f3;
}
</style>
<style lang="scss" scoped>
:deep(.table-header) {
  background-color: #f8faff !important;
}

.supplier {
  padding: 20px 20px;
  width: 100%;
  height: 100%;
  .search {
    display: flex;
    margin-bottom: 20px;
    .search-item {
      margin-right: 20px;
    }
    .search-input {
      width: 200px;
      height: 34px;
    }
  }
  /* .search-button {
    position: fixed;
    top: 110px;
    right: 60px;
    display: flex;
    .btn {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 90px;
      height: 34px;
      padding: 10px;
      // margin-right: 20px;
      font-size: 14px;
      border-radius: 4px;
      user-select: none;
      cursor: pointer;
    }
    .btn.search {
      color: #fff;
      background: rgba(0, 124, 239, 1);
      &:hover {
        background: rgba(0, 124, 239, 0.85);
      }
    }
    .btn.add {
      border: none;
      color: #fff;
      background: rgba(255, 159, 0, 1);
      &:hover {
        background: rgba(255, 159, 0, 0.85);
      }
    }
    .btn.reset {
      color: rgba(43, 193, 123, 1);
      background: rgba(43, 193, 123, 0.05);
      border: 1px solid rgba(43, 193, 123, 1);
      &:hover {
        background: rgba(43, 193, 123, 0.2);
      }
    }
    .icon {
      margin-right: 6px;
    }
  } */
  .material-container {
    display: flex;

    .class-container {
      width: 240px;
      height: 64vh;
      margin-right: 10px;
      padding-top: 30px;
      background: #ffffff;
      box-shadow: 0px 0px 10px 0px rgba(26, 43, 26, 0.1);
      border-radius: 2px;
      overflow: auto;
      .class-top {
        display: flex;
        justify-content: center;
        margin-bottom: 20px;
        .class-input {
          width: 180px;
        }
      }
    }
  }

  .table-icon {
    width: 20px;
    height: 20px;
    cursor: pointer;
  }

  .table-operate {
    width: 100%;
    display: flex;
    justify-content: space-around;
    .table-icon {
      width: 20px;
      height: 20px;
      cursor: pointer;
    }
  }

  .pagination {
    margin: 20px auto;
  }
  :deep(.el-table) {
    th.el-table__cell {
      font-size: 14px;
      font-weight: 400;
      height: 40px;
      color: #333333;
      background: #f8faff !important;
    }
    // 表格高度
    .el-table__cell {
      padding: 0;
      height: 40px;
    }
    .cell.el-tooltip {
      display: flex;
      align-items: center;
    }
  }
  :deep(.el-table--large .cell) {
    padding: 0 20px 0 20px !important;
  }
  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
  }
  .image-slot .el-icon {
    font-size: 30px;
  }
}
</style>
